<template>
  <div class="login-user">
    <el-form
      label-width="70px"
      :model="account"
      :rules="loginUserRules"
      ref="elFormRef"
      class="el-form"
    >
      <el-form-item label="账号" prop="name">
        <el-input v-model="account.name" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="account.password"
          placeholder="请输入密码"
          show-password
        ></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref } from 'vue'
import { ElForm } from 'element-plus'
import { loginUserRules } from '../hooks/rules'
import localCatche from '@/utils/cache'
import { useStore } from 'vuex'
export default defineComponent({
  name: 'LoginUser',
  setup() {
    const store = useStore()
    const account = reactive({
      name: localCatche.getCatche('name'),
      password: localCatche.getCatche('password')
    })
    const elFormRef = ref<InstanceType<typeof ElForm>>()
    // 用户登录
    const loginUserAction = (rememberPassword: boolean) => {
      elFormRef.value?.validate((res) => {
        if (res) {
          // 记住密码
          if (rememberPassword) {
            // console.log('记住密码')
            localCatche.setCache('name', account.name)
            localCatche.setCache('password', account.password)
          } else {
            // 清空
            localCatche.setCache('name', '')
            localCatche.setCache('password', '')
          }

          // 2、登陆验证
          store.dispatch('login/accountLoginAction', { ...account })
        }
      })
    }
    return {
      account,
      elFormRef,
      loginUserRules,
      loginUserAction
    }
  }
})
</script>
<style lang="less" scoped>
.el-form {
  padding-top: 10px;
}
</style>
